package org.qh.common.pay.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class MoneyConversionUtil {

    // 元转分
    public static int yuanToFen(BigDecimal yuan) {
        if (yuan.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("金额不能为负数");
        }
        BigDecimal fenBigDecimal = yuan.multiply(new BigDecimal(100));
        return fenBigDecimal.intValueExact();
    }

    // 分转元
    public static double fenToYuan(long fen) {
        if (fen < 0) {
            throw new IllegalArgumentException("金额不能为负数");
        }
        BigDecimal fenBigDecimal = BigDecimal.valueOf(fen);
        BigDecimal yuanBigDecimal = fenBigDecimal.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        return yuanBigDecimal.doubleValue();
    }

    // 元转换为元角分的字符串形式
    public static String yuanToYuanJiaoFen(BigDecimal yuan) {
        int fen = yuanToFen(yuan);
        int jiao = fen / 10 % 10;
        int yuanInt = fen / 100;
        int fenInt = fen % 10;
        return yuanInt + "元" + jiao + "角" + fenInt + "分";
    }

    // 元角分的字符串形式转换为元
    public static double yuanJiaoFenToYuan(String yuanJiaoFen) {
        String[] split = yuanJiaoFen.split("[元角分]");
        int yuan = Integer.parseInt(split[0]);
        int jiao = Integer.parseInt(split[1]);
        int fen = Integer.parseInt(split[2]);
        return yuan + jiao / 10.0 + fen / 100.0;
    }
}
